package com.yun.blog.interceptor;

import com.yun.blog.bean.Result;
import com.yun.blog.bean.User;
import com.yun.blog.service.UserService;
import com.yun.blog.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * title        : TokenInterceptor
 * projectName  : dantouBlog-back
 * description  : 登录token拦截器，拦截通往admin的请求，检查是否登录及是否是管理员，
 * author       : simple
 * date         : 2022/11/24下午2:28
 */

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${spring.profiles.active}")
    private String env;

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到request.URI = {}", request.getRequestURI());
        if (env.equals("dev")){
            // 不拦截测试请求，header带test属性就放行，部署的时候注释掉这句if代码
            if (request.getHeader("test") != null) {
                return true;
            }
        }

        // 检查header 中带的token是否合法
        if (!JwtUtils.checkToken(request)) {
            Result fail = Result.fail();
            fail.setCode(HttpStatus.UNAUTHORIZED.value());
            fail.setMsg("登录信息验证失败，请重新登录");
            String failJson = fail.toJson();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(failJson);
            return false;
        }
        // 检查是否是超级用户
        User user = userService.getById(JwtUtils.getMemberIdByToken(request));
        if (!user.getIsSuperuser()){
            Result fail = Result.fail();
            fail.setCode(HttpStatus.UNAUTHORIZED.value());
            fail.setMsg("没有后台管理权限，禁止登录管理后台！");
            String failJson = fail.toJson();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.getWriter().write(failJson);
            return false;
        }
        return true;
    }
}
